-- DriftBottleM
-- Created by chengb Jul/20/2015
-- 漂流瓶模块

module("DriftBottleM", package.seeall);

-- 漂流瓶配置
local driftBottleTable = {};
local driftBottleList  = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    driftBottleTable = {};

    -- 转换漂流瓶配置表
    drift_bottle_CSV = get_drift_bottle_CSV();
    for i = 1, #drift_bottle_CSV do
        local id = drift_bottle_CSV[i].id;
        driftBottleTable[id] = drift_bottle_CSV[i];
    end

    drift_bottle_CSV = nil;

    -- 根据id升序
    driftBottleList = table.values(driftBottleTable);
    table.sort(driftBottleList, function(a, b) return a.id < b.id; end);
end

function init()
    loadCsv();
end

-- 检索配置
function query(id, path)
    local m = driftBottleTable[id];

    if not m or path == "" or not path then
        return m;
    end

    return m[path];
end

-- 更新漂流瓶拾取记录
function updateBottleRecord(id)
    local bottleRecord = ME.user.dbase:query("drift_bottle") or {};
    if table.indexOf(bottleRecord, id) == -1 then
        table.insert(bottleRecord, id);
        ME.user.dbase:set("drift_bottle", bottleRecord);

        printTable(bottleRecord, "漂流瓶拾取记录已更新");
    end
end

-- 是否拾取了某个id的漂流瓶
function isBottlePicked(id)
    local bottleRecord = ME.user.dbase:query("drift_bottle") or {};
    if table.indexOf(bottleRecord, id) == -1 then
        return false;
    end
    return true;
end

-- 是否拾取了所有类型的漂流瓶
function isAllBottlePicked()
    local ids = table.keys(driftBottleTable);
    for _, id in pairs(ids) do
        if not isBottlePicked(id) then
            return false;
        end
    end
    return true;
end

-- 抽取漂流瓶id
function fetchBottleId()
    local seed = DungeonM.getRandSeed("fetch_bottle_id");

    local info = fetchElemBySeed(driftBottleList, seed);

    return info.id;
end

-- 执行漂流瓶事件
function doEvent(pos)
    local grid = DungeonM.getGridByPos(pos);
    local gridType = grid.type;

    if not grid then
        trace("DriftBonusM", "位置(%d)的格子不存在。", pos);
        return false;
    end

    if grid.state == GRID_STATE_DISABLE then
        trace("DriftBonusM", "建筑格子(type = %d)已失效。", gridType);
        return false;
    end

    -- 漂流瓶
    local eventBonus = FormulaM.invoke("CALC_DRIFT_BOTTLE_BONUS", ME.user, grid.bonus);

    -- 更新漂流瓶拾取记录
    if grid.can_talk == 1 then
        updateBottleRecord(grid.id);
    end

    -- 执行奖励
    BuildingBonusM.doBuildingBonus(eventBonus, "drift_bottle");

    -- 改变状态
    grid:changeState(GRID_STATE_DISABLE);
    
    if DungeonM.isCostRound(grid) then
        -- 抛出一个回合事件
        EventMgr.fire(event.COMBAT_ROUND, { ["pos"] = pos, ["isDelay"] = true });
    end

    -- 抛出通用建筑奖励事件
    EventMgr.fire(event.COMM_BUILDING_BONUS, {
        ["pos"]   = pos,
        ["type"]  = gridType,
        ["bonus"] = eventBonus,
    });

    -- 通知建筑事件完成
    EventMgr.fire(event.BUILDING_EVENT_DONE, {["pos"] = pos,});
    return true;
end






